package com.crayon.account.loader;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;

import com.crayon.account.dao.DAOTable;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.util.GDB;
import com.google.gson.Gson;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;

import java.util.LinkedList;
import java.util.List;

public class LoaderSQLTableAppend extends AsyncTaskLoader<List<DAOTable>> {


    DAOTable table;
    List<DAOTable> tables;
	public LoaderSQLTableAppend(Context context,DAOTable table) {
		super(context);
        this.table = table;
	}

    public LoaderSQLTableAppend(Context context,List<DAOTable> tables) {
        super(context);
        this.tables = tables;
    }

    @Override
	public List<DAOTable> loadInBackground() {

		DataBaseManager baseManager =DataBaseManager.getHelper(getContext());

        if(table!=null){
            try {
                Dao<DAOTable, Integer> daoTable =baseManager.getDAOTable();
                daoTable.create(table);

            }catch(Exception e ){
                GDB.log(getClass(), "result  err " + e.getMessage());
            }

            try{

                GDB.log(getClass()," table " + new Gson().toJson(table));

            }catch ( Exception e){
                GDB.log(getClass(), "result search err " + e.getMessage());

            }
            this.table=null;
        }
        if(this.tables!=null && this.tables.size()>0){
            try {
                Dao<DAOTable, Integer> daoTable =baseManager.getDAOTable();
                daoTable.delete(tables);
                for(DAOTable item : tables){
                    daoTable.create(item);
                }
            }catch(Exception e ){
                GDB.log(getClass(), "result  err " + e.getMessage());
            }


            this.tables=null;
        }


		return null;
	}

	@Override
	protected void onStartLoading() {
		// TODO Auto-generated method stub
		super.onStartLoading();
		forceLoad();
	}


}


